package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadFileUsingCompletionHandlerAndAsynchronousFileChannel {
	private static Thread current;

	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(100);
		Path path = Paths.get("E:\\Copy", "1.txt");
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.READ)) {
			current = Thread.currentThread();
			asynchronousFileChannel.read(buffer, 0, "读取操作状态 ...",
					new CompletionHandler<Integer, Object>() {
						@Override
						public void completed(Integer result, Object attachment) {
							System.out.println(attachment);
							System.out.print("读取 bytes: " + result);
							current.interrupt();
						}

						@Override
						public void failed(Throwable exc, Object attachment) {
							System.out.println(attachment);
							System.out.println("错误:" + exc);
							current.interrupt();
						}
					});

			System.out.println("等待 ...\n");
			try {
				current.join();
			} catch (InterruptedException ignored) {
			}
			System.out.println("读取结束.");
		} catch (Exception ex) {
			System.err.println(ex);
		}
	}
}
